#include <DHT.h>
#include <Arduino.h>
#include <HardwareSerial.h>
#include <ERxPachube.h>
#include <Ethernet.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
#define BUFSIZ 50
Adafruit_BMP085 bmp;
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT11   // DHT 11 
DHT dht(DHTPIN, DHTTYPE);

///%%**%%%%**%%%%**%%%%**%%%%**%%%%**%% ETHERNET STUFF %%**%%%%**%%%%**%%%%**%%%%**%%%%**%%/
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xEE, 0xDD };
byte ip[] = { 
  10, 0, 0, 179 };
byte gw[] = { 
  10, 0, 0, 2 };
byte subnet[] = { 
  255, 255, 255, 0 };

#define PACHUBE_API_KEY	"hYG1Xg8wGvgnTKfHdm2vp1TeT7iSAKxIb2NGN255RXBUST0g" // fill in your API key PACHUBE_API_KEY
#define PACHUBE_FEED_ID	52900 // fill in your feed id
int pachubestatus=0;

ERxPachubeDataOut dataout(PACHUBE_API_KEY, PACHUBE_FEED_ID);
void PrintDataStream(const ERxPachube& pachube);


EthernetServer webserver(80);
struct Timing {
  unsigned long current;
  unsigned long previous;
  unsigned long Pressure;
  unsigned long Humidity;  
  unsigned long Pachube;    
  int delta;
} 
time = { 
  0, 0, 0, 0, 0, 0};

void setup() {

  Serial.begin(115200);
  Ethernet.begin(mac,ip,subnet,gw);
  bmp.begin();  
  dataout.addData(0);
  dataout.addData(1);
  dataout.addData(2);
  dataout.addData(3);
  dataout.addData(4);  
  pinMode(A0,INPUT);
  dht.begin();
  Serial.println("Loading");
}

float cPressure;
float cTemp;
float cAlt;
float cLight;
float cHumidity;

void updatepachube(){
  dataout.updateData(0, cTemp);
  dataout.updateData(1,cPressure);
  dataout.updateData(2,cAlt);
  dataout.updateData(3,cLight);
  dataout.updateData(4,cHumidity);
  // pachubestatus =
  dataout.updatePachube();
}


void loop() {
  Serial.println(millis());

  time.current = millis();
  time.delta = (int) (time.current - time.previous);
  time.previous = time.current;

  if(time.current > (time.Humidity + 1000)) { // 5 mins
    cHumidity = dht.readHumidity(); 
    time.Humidity = time.current;
  }
  if(time.current > (time.Pachube + 10000)) { // 5 mins
    updatepachube();
    time.Pachube = time.current;
  }  

  if(time.current > (time.Pressure + 1000)) { // 5 mins
    cPressure = bmp.readPressure();
    cTemp = (bmp.readTemperature() + dht.readTemperature()) /2 ;
    cAlt = bmp.readAltitude();
    cLight = analogRead(A0);
    time.Pressure = time.current;
  }
}


int convint(String Data){
  char carray2[Data.length() +1];
  Data.toCharArray(carray2,sizeof(carray2));
  return atoi(carray2); 
}
void PrintDataStream(const ERxPachube& pachube)
{
  unsigned int count = pachube.countDatastreams();
  Serial.print("data count=> ");
  Serial.println(count);

  Serial.println("<id>,<value>");
  for(unsigned int i = 0; i < count; i++)
  {
    Serial.print(pachube.getIdByIndex(i));
    Serial.print(",");
    Serial.print(pachube.getValueByIndex(i));
    Serial.println();
  }
}

